package com.five;

import com.five.mapper.ReadHistoryMapper;
import com.five.pojo.ReadHistory;
import com.five.util.NovelIndexInitializer;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.LocalDateTime;
import java.util.List;
import static org.hibernate.validator.internal.util.Contracts.assertNotNull;

/**
 * Elasticsearch 索引创建客户端（用于运行 NovelIndexInitializer）
 *
 */

@SpringBootTest(classes = ReadApp.class)
@MapperScan("com.five.mapper") // 扫描 Mapper 接口
@ExtendWith(MockitoExtension.class)
public class ElasticsearchClientRunner {

    public static void main(String[] args) {
        // 1. 初始化 Elasticsearch 客户端（根据实际 ES 服务地址配置）
        RestHighLevelClient client = null;
        try {
            // 配置 ES 服务地址：默认本地 9200 端口，如需连接远程，修改为实际 IP 和端口
            client = new RestHighLevelClient(
                RestClient.builder(
                    new HttpHost("localhost", 9201, "http")
                )
            );

            // 2. 调用索引创建工具类，创建小说索引
            System.out.println("开始创建索引...");
            NovelIndexInitializer.createIndex(client);
            System.out.println("索引创建流程执行完成");

        } catch (Exception e) {
            // 3. 处理异常（如连接失败、索引已存在等）
            System.err.println("索引创建失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 4. 关闭客户端，释放资源（必须执行）
            if (client != null) {
                try {
                    client.close();
                    System.out.println("客户端已关闭");
                } catch (Exception e) {
                    System.err.println("客户端关闭失败：" + e.getMessage());
                }
            }
        }
    }

    @Autowired
    private ReadHistoryMapper readHistoryMapper;

    @Test
    void addReadHistory() {
        ReadHistory history = new ReadHistory();
        history.setReaderId(1L);
        history.setNovelId(100L);
        history.setChapterId(5L);
        history.setCreateTime(LocalDateTime.now());

        readHistoryMapper.addReadHistory(history);
        // 可通过查询验证插入结果
    }


    @Test
    void queryReadHistory() {
        Long userId = 1L;
        List<ReadHistory> histories = readHistoryMapper.queryReadHistory(userId);
        assertNotNull(histories);
        // 验证结果是否为一周内数据
    }




}